#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogModule;


const int gdefaultfd = -1;
#define MAX 4096


// 最开始的时候,我们的服务器,只有一个文件描述符
class PollServer
{
public:
    PollServer(int port) : _port(port),
                             _listen_socket(std::make_unique<TcpSocket>()),
                             _isrunning(false)
    {
    }
    void Init()
    {
        _listen_socket->BuildTcpSocket(_port);
        for(int i = 0;i < MAX;i++)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        //先把唯一的fd添加到poll中
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
        //revents是交给我们对应的内核进行设置的
    }
    void Loop()
    {
        int timeout = 10000;
        _isrunning = true;
        while (_isrunning)
        {
            int n = poll(_fds,MAX,timeout);
            //完成通知上层的任务
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                // rfds: 内核告诉用户,你关心的rfds中的fd,有哪些已经就绪了
                Dispatcher();
                //将已经就绪的sockfd,派发给指定的模块
                TestFd();
                break;
            }
        }
        _isrunning = false;
    }
    void Accepter()
    {
        InetAddr client;
        // listensockfd就绪了! 再获取新连接
        int newfd = _listen_socket->Accepter(&client);
        // 这里进行accept不会被阻塞了,因为我们是被select叫来的,只执行拷贝
        if (newfd < 0)
        {
            return;
        }
        else
        {
            std::cout << "获取了一个新的连接: " << newfd << " client info: " << client.Addr() << std::endl;
            // 添加新的newfd
            int pos = -1;
            for (int j = 0; j < MAX; j++)
            {
                if (_fds[j].fd == gdefaultfd)
                {
                    pos = j;
                    break;
                }
            }
            if (pos == -1)
            {
                LOG(LogLevel::ERROR) << "服务器已经满了...";
                //_fds可以进行自动的扩容(这里我们就不进行操作了)
                close(newfd);
            }
            else
            {
                _fds[pos].fd = newfd;
                _fds[pos].fd = POLLIN;
            }
        }
    }
    void Recver(int who)
    {
        char buffer[1024];
        ssize_t n = recv(_fds[who].fd,buffer,sizeof(buffer)-1,0);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client# " <<buffer << std::endl;
            std::string message = "echo# ";
            message += buffer;
            send(_fds[who].fd,message.c_str(),message.size(),0);
        }
        else if(n == 0)
        {
            LOG(LogLevel::DEBUG) << "客户端退出, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << _fds[who].fd;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_fds[i].fd == gdefaultfd)
            {
                continue;
            }
            if (_fds[i].fd == _listen_socket->Fd())
            {
                if (_fds[i].revents & POLLIN)
                {
                    Accepter();
                }
            }
            else
            {
                if (_fds[i].revents & POLLIN)
                {
                    Recver(i);
                }
                // else if(_fds[i].revents & POLLOUT)
                // {
                //     //write
                // }
            }
        }
    }
    void TestFd()
    {
        std::cout << "pollfd: ";
        for(int i = 0;i < MAX;i++)
        {
            if(_fds[i].fd == gdefaultfd)
            {
                continue;
            }
            std::cout << _fds[i].fd << "[" << EventsToString(_fds[i].events) << "] ";
        }
        std::cout << "\n";
    }
    std::string EventsToString(short events)
    {
        std::string s = (events & POLLIN) ? "POLLIN" : "";
        s += (events & POLLOUT) ? "POLLOUT" : "";
        return s;
    }
    ~PollServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_socket;
    bool _isrunning;
    struct pollfd _fds[MAX];
    // struct pollfd* _fds;  -->  malloc
};
